<?php
class FileUploader
{
    static private $_url;
    static private $_dir;
    static private $fileTypes  = array(  
        'image/pjpeg'     => 'jpg',
        'image/jpeg'     => 'jpg',
        'image/jpeg'     => 'jpeg',
        'image/gif'     => 'gif',
        'image/X-PNG'    => 'png',
        'image/PNG'         => 'png',
        'image/png'     => 'png',
        'image/x-png'     => 'png',
        'image/JPG'     => 'jpg',
        'image/GIF'     => 'gif',
        'image/bmp'     => 'bmp',
    );

    static public function setDir($dir)
    {
        self::$_dir = $dir;
    }

    static public function setUrl($url)
    {
        self::$_url = $url;
    }

    static public function getFileInfo($name, $userId)
    {
        $files = $_FILES;
        $info = isset($files[$name])?$files[$name]:'';
        $res = array();
        if (self::isValid($info))
        {
            $filename = self::saveToLocal($info, $userId);
            $res['imgurl'] = self::$_url.$filename;
            $res['imgid'] = $userId;
            return $res;
        }
        return false;
    }

    static private function isValid($info)
    {
        return ( (''!=$info) && (0==$info["error"]) && is_uploaded_file($info['tmp_name'])
            && (0<$info["size"]) && (''!=$info["name"]) && self::isAllowType($info['tmp_name']) );
    }

    static private function getFileType($file)
    {
        $imgInfo = getimagesize($file);
        return $imgInfo['mime'];
    }

    static private function getFileExt($file)
    {
        $tmp = explode("/", self::getFileType($file));
        return $tmp[1];
    }

    static private function isAllowType($file)
    {
        $picExt = self::getFileType($file);
        return isset(self::$fileTypes[$picExt]);
    }

    static private function saveToImgServer($info)
    {
        $result = '';
        $fp = fopen($info["tmp_name"], "r");
        $picdata = base64_encode(fread($fp, filesize($info["tmp_name"])));
        $imgInfo = getimagesize($info["tmp_name"]);
        $args['data'] = $picdata;
        $tmp = explode("/", $imgInfo['mime']);
        $picExt = $tmp[1];
        $args['ext'] = $picExt;
        var_dump($args);
        exit;
        //remoting call start
        //...
    }

    static private function saveToLocal($info, $userId)
    {
        $filename = $userId.'.'.self::getFileExt($info['tmp_name']);
        move_uploaded_file($info['tmp_name'], self::$_dir.$filename);
        return $filename;
    }
}
